package com.ling.tools.login.service.Impl;

import com.ling.tools.login.mapper.UserDao;
import com.ling.tools.login.entity.User;
import com.ling.tools.login.service.UserService;
import com.ling.tools.login.utils.PwdUtils;
import com.ling.tools.login.utils.Result;
import com.ling.tools.login.utils.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;


@Service
public class UserServiceImpl implements UserService {


    @Autowired(required = false)
    private UserDao userDao;







    @Override
    public Result saveUser(User user) {
        Result r = new Result();
        String accout = user.getAccount();
        User userInfo = userDao.findUserInfoByAccount(accout);
        System.out.println("查询结果为" + userInfo);
        if(null != userInfo){
            r.setResultCode(ResultCode.USER_ALREADY_EXISTS);
        }else{
            PwdUtils.pwdEncryption(user);
            int index = new Random().nextInt(6)+1;
            String userHeader = "static/header/user_"+index+".png";
            user.setUserHeader(userHeader);
            userDao.saveUser(user);
            r.setResultCode(ResultCode.SUCCESS);
        }

        return r;
    }

    @Override
    public Result executeLogin(User user) {
        Subject subject = SecurityUtils.getSubject();
        Result result = new Result();
        User userInfo = userDao.findUserInfoByAccount(user.getAccount());

        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),user.getPassword());
        subject.login(token);
        return result;
    }

    @Override
    public User findUserByAccount(String account) {
        return userDao.findUserInfoByAccount(account);
    }


}
